using System;
using System.IO;
using UnityEditor;
using UnityEditor.Experimental.GraphView;
using UnityEngine;
using UnityEngine.UIElements;

namespace DA.AnimGraph.Editor {
    public partial class AnimGraphEditorWindow : GraphViewEditorWindow {

        private AGEEnvironment ageEnv;
        private string path;
        private FramePane framePane;
        public bool isValid { get; private set; }
        public bool hasContext => ageEnv.ageContext != null;
        public string titleText => ageEnv?.ageContext?.titleText;
        public AGEContext GetContext() => ageEnv?.ageContext;

        private void OnEnable() {
            SetTitle("Anim Graph Editor");
            minSize = new Vector2(1200, 600);
            if (!string.IsNullOrEmpty(path)) {
                if (File.Exists(path)) {
                    try {
                        InitWithPath(path);
                    }
                    catch (Exception e) {
                        // 点击运行导致编辑器弹窗提醒保存，若保存，在重新开启时文件会读出null，延迟一帧可解
                        isValid = false;
                        EditorApplication.delayCall = () => InitWithPath(path);
                    }
                    return;
                }
            }
            InitWithPath(null);
            //EditorApplication.update += OnEditorUpdate;
        }

        private void OnDisable() {
            //EditorApplication.update -= OnEditorUpdate;
            framePane.Close();
            ageEnv.OnDisable();
            ageEnv = null;
            isValid = false;
        }

        private void InitWithPath(string path) {
            if (this.path != path) {
                rootVisualElement.Clear();
                ageEnv?.OnDisable();
                ageEnv = null;
                framePane = null;
                isValid = false;
            }
            if (isValid) return;
            isValid = true;
            this.path = path;

            ageEnv = new(this);
            if (path != null) {
                ageEnv.InitContext(path);
            }

            if (framePane == null) {
                framePane = new FramePane(ageEnv);
                framePane.StretchToParentSize();
                rootVisualElement.Add(framePane);
            }
            framePane.Init();
        }

        private void Update() {
            ageEnv.ageContext?.Update();
            framePane?.Update();
        }

        internal void SetTitle(string newText) {
            titleContent.text = newText;
        }

        internal void SaveIfDirty() {
            ageEnv.ageContext?.SaveIfDirty();
        }
    }
}